import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import {
  Modal,
  Button,
  Form,
  message,
  Input,
  DatePicker,
  Select,
  InputNumber,
  Table,
  Card,
} from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';
import { getDictOptionsByCode } from '@/support/common';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { ColumnsType } from 'antd/es/table';
import PateoSearchForm from '@/components/common/PateoSearchForm';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  dataClassManagSelectDataModal: state.dataClassManagSelectDataModal,
  loading: state.loading.effects['dataClassManagSelectDataModal/postFetchPage'],
});
class _SelectDataModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      formData: {},
      pagination: {
        current:1,
        pageSize:10,
      }
    };
  }
  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.fetchPage();
    }
  }
  close = () => {
    const { closeModal } = this.props;
    closeModal('add');
  };
  handleTableChange = (pagination: any, filters: any={}) => {
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState(pagination);
    const params = {
      number: current,
      size: pageSize,
      ...formValues,
      ...filters,
    };
    this.fetchPage(params);
  };
  handleFormReset = () => {
  };
  fetchPage = (params: any = {}) => {
    const { dispatch } = this.props;
    const {
      location: { query },
    } = this.props;
    params.dataClassId = query.id;
    dispatch({
      type: 'dataClassManagSelectDataModal/postFetchPage',
      payload: { url: '/dataheader/itemlist', ...params },
    });
  };
  render() {
    const { modalVisible,pagination: _pagination} = this.props;
    const {
      dataClassManagSelectDataModal: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
      location: { query },
    } = this.props;
    const columns: ColumnsType<any> = [
      {
        title: '序号',
        dataIndex: 'rowNumber',
        width: 40,
      },
      {
        title: '数据对象',
        dataIndex: 'dataObj',
        width: 150,
        ellipsis: true,
      },

      {
        title: '数据类别',
        dataIndex: 'dataCag',
        width: 150,
        ellipsis: true,
      },
      {
        title: '字段名称',
        dataIndex: 'fieldName',
        width: 150,
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [];
          if (record.status == '1') {
            btns.push({
              title: '选中',
              key: 'add',
              auth: 'classDetail-opt',
              onConfirm: () => {
                const postData = {
                  dataClassId: query.id,
                  dataFieldId: record.id,
                  dataCagHeader: record.dataCag,
                  fieldNameHeader: record.fieldName,
                };
                dispatch({
                  type: 'dataClassManagSelectDataModal/postObjWithRes',
                  payload: {
                    url: '/dataheader/add',
                    ...postData,
                  },
                  callback: res => {
                    if (res.statusCode === '0') {
                      message.success('新增成功');
                      this.handleTableChange(pagination)
                    }
                  },
                });
              },
            });
          } else {
            btns.push({
              title: '移除',
              key: 'del',
              auth: 'classDetail-opt',
              onConfirm: () => {
                dispatch({
                  type: 'dataClassManagSelectDataModal/postObjWithRes',
                  payload: {
                    url: '/dataheader/delete',
                    id: record.id,
                  },
                  callback: res => {
                    if (res.statusCode === '0') {
                      message.success('移除成功');
                      this.handleTableChange(pagination);
                    }
                  },
                });
              },
            });
          }
          // btns.push(revokeBtn);
          return <PateoAuthButtons btns={btns} pathname={this.props.location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '数据字段',
        key: 'search',
        placeholder: '请输入对象、类别或字段名称',
      },
    ];

    return (
      <Modal
        title={'选择数据字段'}
        // footer={footer}
        visible={modalVisible}
        width={1100}
        onCancel={() => this.close()}
        onOk={() => this.close()}
        cancelButtonProps={{ hidden: true }}
      >
        <Card bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'dataClassManagSelectDataModal/postFetchPage',
              url: '/dataheader/itemlist',
            }}
            extraArgs={{ dataClassId: query.id }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {/* add */}
          {/* <div>
            {filterAuth('classDetail-opt', this.context.permissions, this.props.location.pathname) ? (

            ) : null}
          </div> */}
          <div className="my_newItem">
            {/* <Button
              type="primary"
              size="small"
              onClick={() => this.setState({ exportVisible: true })}
            >
              导入
            </Button> */}
          </div>
          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: '100%' }}
          />
        </Card>
      </Modal>
    );
  }
}
export const SelectDataModal = connect(mapStateToProps)(_SelectDataModal);
